#!/bin/bash -eu
#
# Copyright 2020 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

# Get provided attributes.
readonly ERPNEXT_ADMIN_PASSWORD="$(get_attribute_value "erpnext-admin-password")"
readonly MYSQL_ROOT_PASSWORD="$(get_attribute_value "mysql-root-password")"
readonly FRAPPE_PASSWORD="$(get_attribute_value "frappe-user-password")"


# Change frappe user password.
FRAPPE_USER="frappe"
echo "${FRAPPE_USER}:${FRAPPE_PASSWORD}" | chpasswd

# Change erpnext admin password.
su - ${FRAPPE_USER} -c "cd frappe-bench && bench set-admin-password ${ERPNEXT_ADMIN_PASSWORD}"

# Change mysql root password.
readonly INITIAL_PASSWORD_FILE="/mysql_initial_password"
readonly MYSQL_INITIAL_PASSWORD="$(cat ${INITIAL_PASSWORD_FILE})"

mysql --user=root --password="${MYSQL_INITIAL_PASSWORD}" --host=localhost mysql <<-EOSQL
  ALTER USER 'root'@'localhost' IDENTIFIED BY "${MYSQL_ROOT_PASSWORD}";
  FLUSH PRIVILEGES;
EOSQL

# Cleanup mysql initial password file.
rm -f "${INITIAL_PASSWORD_FILE}"

supervisorctl restart all

# Wait until ready.
until curl "http://localhost:80"; do
  sleep 3
done
